#!/bin/bash
#set -x

# 修改 wwwroot 权限
chown -R www:www /data

# create folders and set correct permissions
if [ ! -d /run/mysqld ]; then
  mkdir -p /run/mysqld
  chmod -R 0755 /run/mysqld
  chown -R mysql:root /run/mysqld
fi

if [ ! -d /var/log/mysql ]; then
  mkdir -p /var/log/mysql
  chmod -R 0755 /var/log/mysql
  chown -R mysql:mysql /var/log/mysql
fi

# initialize mysql database
if [ "`ls -A /var/lib/mysql`" = "" ]; then
  echo -e >&2 "Starting to initialize the database..."
  if [ -z "$MYSQL_ROOT_PASSWORD" ]; then
      echo >&2 'error: database is uninitialized and password option is not specified '
      echo >&2 'Environment variables MYSQL_ROOT_PASSWORD need to be set!'
      exit 1
  fi
  # create folders as we don't have any today
  mkdir -p /var/lib/mysql
  chmod -R 0700 /var/lib/mysql
  chown -R mysql:mysql /var/lib/mysql

  # initialize database  --user mysql
  mysqld --initialize-insecure

  # start mysql server
  /usr/bin/mysqld_safe >/dev/null 2>&1 &

  for i in {60..0}; do
      if mysqladmin -uroot ping &> /dev/null; then
          break
      fi
      if [ $i = "60" ]; then
          echo >&2 'MySQL init process in progress...'
      fi
      if [ $i = "0" ]; then
          echo >&2 "MySQL fail to start"
          exit 1
      fi
      sleep 1
  done

  # creating debian-sys-maint user without password
  # 创建外部可访问的 root 用户，修改本地 root 用户的密码
  mysql <<-EOSQL
    CREATE USER 'debian-sys-maint'@'localhost' IDENTIFIED BY '';
    GRANT ALL PRIVILEGES on *.* TO 'debian-sys-maint'@'localhost' WITH GRANT OPTION;
    CREATE USER 'root'@'%' IDENTIFIED BY '${MYSQL_ROOT_PASSWORD}';
    GRANT ALL ON *.* TO 'root'@'%' WITH GRANT OPTION;
    ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY "${MYSQL_ROOT_PASSWORD}";
    GRANT ALL ON *.* TO 'root'@'localhost' WITH GRANT OPTION ; FLUSH PRIVILEGES;
EOSQL
  
  # 创建数据库
  if [ ! -z "$MYSQL_DATABASE" ]; then
      mysql --defaults-file=/etc/mysql/debian.cnf -e "CREATE DATABASE IF NOT EXISTS \`$MYSQL_DATABASE\` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;"
  fi

  # 如有有初始化 sql，则执行
  for f in /init/*; do
      case "$f" in
          *.sql)    echo "running $f"; mysql --defaults-file=/etc/mysql/debian.cnf < "$f"; echo ;;
          *)        echo "ignoring $f" ;;
      esac
      echo
  done

  /usr/bin/mysqladmin --defaults-file=/etc/mysql/debian.cnf shutdown
  echo -e >&2 "Initialization completed, some other settings are in progress..."
fi

echo -e >&2 "Congratulations, startup completed！"
/usr/bin/mysqld_safe
